﻿package doue.interactive{
	import flash.display.Sprite;
	import flash.utils.getDefinitionByName;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;

	public class SampleSpider extends Sprite {
		private var __Spider:Class;
		private var spider:MovieClip;
		private var lineA1:Sprite;
		private var lineA2:Sprite;
		private var centerAX:Number;
		private var centerAY:Number;
		private var speed:Number = 10;

		public function SampleSpider() {
			initView();
			this.addEventListener(Event.ENTER_FRAME, drawLine);
			this.addEventListener(Event.ENTER_FRAME, moveSpider);
			//鼠标点击后，停止侦听ENTER_FRAME事件
			//this.stage.addEventListener(MouseEvent.CLICK, stopAnimation);
			addChild(menuA_mc);
		}
		private function initView():void {
			//获取库元件自动绑定的类
			__Spider = getDefinitionByName("Spider_mc") as Class;
			
			//生成线的容器
			lineA1 = new Sprite();
			lineA2 = new Sprite();
			addChild(lineA1);
			addChild(lineA2);
			centerAX = 240;
			centerAY = 335;
			//
			spider = new __Spider();
			addChild(spider);
			spider.cacheAsBitmap = true;//打开位图缓存，提高执行效率
		}
		//在每帧中，重新绘制蛛丝
		private function drawLine(evt:Event):void {
			lineA1.graphics.clear();//清空
			lineA1.graphics.moveTo(120, 0);
			lineA1.graphics.lineStyle(15, 0x000, 100);
			lineA1.graphics.lineTo(centerAX, centerAX);

			lineA2.graphics.clear();//清空
			lineA2.graphics.moveTo(175, 600);
			lineA2.graphics.lineStyle(15, 0x000, 100);
			lineA2.graphics.lineTo(centerAX, centerAX);
		}
		//在每帧中，移动和旋转蜘蛛
		private function moveSpider(evt:Event):void {
			var dx:Number = this.mouseX - spider.x;
			var dy:Number = this.mouseY - spider.y;
			var p:Number  =Math.atan(dy/dx)*180/Math.PI;
			var rotateAngle:Number = (dx>0) ? (90+p):(270+p);
			spider.x += dx/speed;
			spider.rotation = rotateAngle;
			spider.y += dy/speed;
		}
		private function stopAnimation(evt:MouseEvent):void {
			this.removeEventListener(Event.ENTER_FRAME, drawLine);
			this.removeEventListener(Event.ENTER_FRAME, moveSpider);
		}
	}
}